package com.yc.dygang.dao;

import com.yc.common.util.DBHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MovieDao {

    public List<Map<String, Object>> selectByCategory(String category) {
        String sql = "select * from dyg_movie" +
                " where category=?" +
                " order by create_date desc" +
                " limit 0,16";
        List<Map<String, Object>> list = DBHelper.selectListMap(sql, category);
        return list;
    }

    public Map<String, Object> selectById(String id) {
        String sql = "select * from dyg_movie where id=?";
        return DBHelper.selectOneMap(sql, id);
    }

    /**
     * 分页 + 组合条件查询
     *
     * @param name
     * @param category
     * @param page     第几页
     * @return
     */
    public Map<String, Object> selectByNameAndCategory(String name, String category, String page) {
        String sql = "select * from dyg_movie where 1=1";
        List<Object> params = new ArrayList<>();
        if (name != null && name.trim().isEmpty() == false) {
            name = name.trim();
            name = "%" + name + "%";
            sql += " and ( name like ? or name0 like ? or names like ? or intro like ? )";
            params.add(name);
            params.add(name);
            params.add(name);
            params.add(name);
        }
        if (category != null && category.trim().isEmpty() == false) {
            sql += " and category = ?";
            params.add(category);
        }

        // 查询总行数
        long count = DBHelper.count(sql, params.toArray());
        int ipage = Integer.parseInt(page);
        ipage = (ipage - 1) * 10;
        sql += " limit " + ipage + ",10";
        List<Map<String, Object>> list = DBHelper.selectListMap(sql, params.toArray());

        Map<String, Object> ret = new HashMap<>();
        ret.put("total", count);
        ret.put("data", list);

        return ret;
    }

}
